package com.legna.mhxy.support.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.legna.mhxy.support.dao.ProfitWorthDao;
import com.legna.mhxy.support.dao.RingTaskDao;
import com.legna.mhxy.support.dao.TaskProfitDao;
import com.legna.mhxy.support.entity.ProfitWorth;
import com.legna.mhxy.support.entity.RingTask;
import com.legna.mhxy.support.entity.TaskProfit;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Service
@AllArgsConstructor
@Slf4j
public class TaskService {
    private final RingTaskDao ringTaskDao;
    private final ProfitWorthDao profitWorthDao;
    private final TaskProfitDao taskProfitDao;


    public void createTask(RingTask ringTask){
        ringTaskDao.insert(ringTask);
    }
    public void finishTask(Long taskId){
        RingTask ringTask = ringTaskDao.selectById(taskId);
        ringTask.setStatus(0);
        ringTaskDao.updateById(ringTask);
    }
    public RingTask getByUserId(Long userId){
        return ringTaskDao.selectOne(
                new LambdaQueryWrapper<RingTask>()
                        .eq(RingTask::getUserId,userId)
                        .eq(RingTask::getStatus,1)
                        .last("limit 1"));
    }

    public void addCost(Long taskId, Double cost) {
        RingTask ringTask = ringTaskDao.selectById(taskId);
        Double mhbCost = ringTask.getMhbCost();
        mhbCost += cost;
        ringTask.setMhbCost(mhbCost);
        ringTaskDao.updateById(ringTask);
    }

    public void addProfit(TaskProfit taskProfit) {
        ProfitWorth profitWorth = profitWorthDao.selectOne(new LambdaQueryWrapper<ProfitWorth>()
                .eq(ProfitWorth::getType, taskProfit.getType())
                .eq(ProfitWorth::getGrade,taskProfit.getGrade())
                .eq(ProfitWorth::getCategoryId,taskProfit.getCategoryId())
                .last("limit 1"));
        if (profitWorth == null){
            if (taskProfit.getWorth() != null){
                profitWorth = new ProfitWorth();
                profitWorth.setWorth(taskProfit.getWorth());
                profitWorth.setGrade(taskProfit.getGrade());
                profitWorth.setCategoryId(taskProfit.getCategoryId());
                profitWorth.setType(taskProfit.getType());
                profitWorthDao.insert(profitWorth);
            }
        }else{
            if (taskProfit.getWorth() != null){
                profitWorth.setWorth(taskProfit.getWorth());
                profitWorthDao.updateById(profitWorth);
            }else{
                taskProfit.setWorth(profitWorth.getWorth());
            }
        }
        taskProfitDao.insert(taskProfit);
    }
}
